package com.controler.joystick;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import java.text.DecimalFormat;

/**
 * TODO: document your custom view class.
 */
public class RockerTouch extends View {
    private String mExampleString; // TODO: use a default from R.string...
    private int mExampleColor = Color.RED; // TODO: use a default from R.color...
    private float mExampleDimension = 0; // TODO: use a default from R.dimen...
    private Drawable mExampleDrawable;

    private TextPaint mTextPaint;
    private float mTextWidth;
    private float mTextHeight;

    /* 自定义变量 */
    private Bitmap mOuterBgBitmap;
    private Bitmap mRockerPointBitmap;

    private float innerCenterX;
    private float innerCenterY;

    /* 画笔 */
    private Paint mOuterBgPaint;
    private Paint mRockerPointPaint;

    private float touch_x,touch_y;

    private float max_rad;
    private float max_speed;

    private float speed;
    private float deg;

//    DecimalFormat df2;

    public float getSpeed() {
        return speed;
    }

    public float getDeg() {
        return deg;
    }

    public RockerTouch(Context context) {
        super(context);
        initPaint();
        init(null, 0);
        touch_x = 0;
        touch_y = 0;
    }

    public RockerTouch(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
        init(attrs, 0);
        touch_x = 0;
        touch_y = 0;
    }

    private void initPaint() {
        mOuterBgPaint = new Paint();
        mOuterBgPaint.setAntiAlias(true);
        mOuterBgPaint.setFilterBitmap(true);
        mOuterBgPaint.setColor(Color.RED);
        mOuterBgPaint.setStrokeWidth(10);
        mOuterBgPaint.setStyle(Paint.Style.STROKE);

        mRockerPointPaint = new Paint();
        mRockerPointPaint.setAntiAlias(true);
        mRockerPointPaint.setFilterBitmap(true);
        mRockerPointPaint.setColor(Color.WHITE);

        // Set up a default TextPaint object
        mTextPaint = new TextPaint();
        mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
//        mTextPaint.setTextAlign(Paint.Align.LEFT);
        mTextPaint.setColor(Color.RED);
        mTextPaint.setStyle(Paint.Style.FILL);

        max_rad = 30;   //最大角度   角度制
        // 160rpm ->160/60 rps   160/60*0.12*2*pi =             // 半径12cm   最高速度  2.0106192982974673
        max_speed = 2;

        speed = 0;
        deg = 0;

//        df2 = new DecimalFormat("###.00");

    }

    public RockerTouch(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initPaint();
        init(attrs, defStyle);
        touch_x = 0;
        touch_y = 0;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
//        return super.onTouchEvent(event);
        /* 触摸事件 */
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_x = event.getX();;
                touch_y = event.getY();
                invalidate();
//                innerCenterX = touchDownX = event.getX();
//                innerCenterY = touchDownY = event.getY();
//                checkTouchDownPoint(touchDownX, touchDownY);
//                Log.d("rocker down","x="+event.getX()+"y="+event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
//                updateMoveStatus(event);
//                Log.d("rocker move","x="+event.getX()+"y="+event.getY());
                touch_x = event.getX();;
                touch_y = event.getY();
//                Log.d("rocker move","x="+touch_x+"y="+touch_y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
//                innerCenterX = 0;
//                innerCenterY = 0;
//                touchDownX = 0;
//                touchDownY = 0;
//                keepDeading = true;
                touch_x = 0;
                touch_y = 0;
                invalidate();
                break;
        }
        return true;
    }



    private void init(AttributeSet attrs, int defStyle) {
        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.RockerTouch, defStyle, 0);

        mExampleString = a.getString(
                R.styleable.RockerTouch_exampleString);
        mExampleColor = a.getColor(
                R.styleable.RockerTouch_exampleColor,
                mExampleColor);
        // Use getDimensionPixelSize or getDimensionPixelOffset when dealing with
        // values that should fall on pixel boundaries.
        mExampleDimension = a.getDimension(
                R.styleable.RockerTouch_exampleDimension,
                mExampleDimension);

        if (a.hasValue(R.styleable.RockerTouch_exampleDrawable)) {
            mExampleDrawable = a.getDrawable(
                    R.styleable.RockerTouch_exampleDrawable);
            mExampleDrawable.setCallback(this);
        }
        a.recycle();

        // Update TextPaint and text measurements from attributes
        invalidateTextPaintAndMeasurements();
    }

    private void invalidateTextPaintAndMeasurements() {
        mTextPaint.setTextSize(mExampleDimension);
        mTextPaint.setColor(mExampleColor);
        mTextWidth = mTextPaint.measureText(mExampleString);

        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        mTextHeight = fontMetrics.bottom;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // TODO: consider storing these as member variables to reduce
        // allocations per draw cycle.
        int paddingLeft = getPaddingLeft();
        int paddingTop = getPaddingTop();
        int paddingRight = getPaddingRight();
        int paddingBottom = getPaddingBottom();

        int contentWidth = getWidth() - paddingLeft - paddingRight;
        int contentHeight = getHeight() - paddingTop - paddingBottom;

        int center_x = contentWidth/2;
        int center_y = contentHeight/2;
        int min = contentHeight > contentWidth?contentWidth:contentHeight;   //取最小的
        min /= 2.5f;

        float left = paddingLeft + center_x - min;
        float top = paddingTop + center_y - min;
        float right = paddingLeft + center_x + min;
        float bottom = paddingTop + center_y + min;

        float radius = min/5.f;

        if((touch_x == 0) && (touch_y == 0))
        {
            touch_x = paddingLeft + center_x;
            touch_y = paddingTop + center_y;
        }else{
            if(touch_x < left){
                touch_x = left;
            }else if(touch_x > right){
                touch_x = right;
            }
            if(touch_y < top){
                touch_y = top;
            }else if(touch_y > bottom){
                touch_y = bottom;
            }
        }

        // Draw the example drawable on top of the text.
        if (mExampleDrawable != null) {
            mExampleDrawable.setBounds(paddingLeft, paddingTop,
                    paddingLeft + contentWidth, paddingTop + contentHeight);
            mExampleDrawable.draw(canvas);
        }
        /* 得到高宽 */
        canvas.drawRect(new RectF(left,top,right,bottom),mOuterBgPaint);
//        canvas.drawCircle(paddingLeft + center_x,paddingTop + center_y,radius,mRockerPointPaint);
        canvas.drawCircle(touch_x,touch_y,radius,mRockerPointPaint);
//        Log.d("rocker draw","x="+touch_x+"y="+touch_y);
        // Draw the text.
        deg = -(touch_x - center_x - paddingLeft)/min*max_rad;
        speed = -(touch_y - center_y - paddingTop)/min*max_speed;

        canvas.drawText("转角:"+deg+" "+"速度:"+speed,paddingLeft,paddingTop+60,mTextPaint);
    }

    /**
     * Gets the example string attribute value.
     *
     * @return The example string attribute value.
     */
    public String getExampleString() {
        return mExampleString;
    }

    /**
     * Sets the view"s example string attribute value. In the example view, this string
     * is the text to draw.
     *
     * @param exampleString The example string attribute value to use.
     */
    public void setExampleString(String exampleString) {
        mExampleString = exampleString;
        invalidateTextPaintAndMeasurements();
    }

    /**
     * Gets the example color attribute value.
     *
     * @return The example color attribute value.
     */
    public int getExampleColor() {
        return mExampleColor;
    }

    /**
     * Sets the view"s example color attribute value. In the example view, this color
     * is the font color.
     *
     * @param exampleColor The example color attribute value to use.
     */
    public void setExampleColor(int exampleColor) {
        mExampleColor = exampleColor;
        invalidateTextPaintAndMeasurements();
    }

    /**
     * Gets the example dimension attribute value.
     *
     * @return The example dimension attribute value.
     */
    public float getExampleDimension() {
        return mExampleDimension;
    }

    /**
     * Sets the view"s example dimension attribute value. In the example view, this dimension
     * is the font size.
     *
     * @param exampleDimension The example dimension attribute value to use.
     */
    public void setExampleDimension(float exampleDimension) {
        mExampleDimension = exampleDimension;
        invalidateTextPaintAndMeasurements();
    }

    /**
     * Gets the example drawable attribute value.
     *
     * @return The example drawable attribute value.
     */
    public Drawable getExampleDrawable() {
        return mExampleDrawable;
    }

    /**
     * Sets the view"s example drawable attribute value. In the example view, this drawable is
     * drawn above the text.
     *
     * @param exampleDrawable The example drawable attribute value to use.
     */
    public void setExampleDrawable(Drawable exampleDrawable) {
        mExampleDrawable = exampleDrawable;
    }
}